<template>

  <div class="stock-container">

    <!-- 统计卡片区域 -->

    <div class="statistics-area">

      <el-row :gutter="20">

        <el-col :span="6">

          <el-card shadow="hover" class="statistic-card">

            <div class="statistic-content">

              <div class="statistic-title">总库存数量</div>

              <div class="statistic-value">{{ stats.totalStock }}</div>

            </div>

          </el-card>

        </el-col>

        <el-col :span="6">

          <el-card shadow="hover" class="statistic-card">

            <div class="statistic-content">

              <div class="statistic-title">本月入库</div>

              <div class="statistic-value green">+{{ stats.monthlyIn }}</div>

            </div>

          </el-card>

        </el-col>

        <el-col :span="6">

          <el-card shadow="hover" class="statistic-card">

            <div class="statistic-content">

              <div class="statistic-title">本月出库</div>

              <div class="statistic-value red">{{ stats.monthlyOut }}</div>

            </div>

          </el-card>

        </el-col>

        <el-col :span="6">

          <el-card shadow="hover" class="statistic-card">

            <div class="statistic-content">

              <div class="statistic-title">预警数量</div>

              <div class="statistic-value orange">{{ stats.monthlyAdjust }}</div>

            </div>

          </el-card>

        </el-col>

      </el-row>

    </div>



    <!-- 搜索区域 -->

    <el-card class="search-area">

      <el-form :inline="true" :model="queryForm" class="demo-form-inline">

        <el-form-item label="药品名称">

          <el-input v-model="queryForm.medicineName" placeholder="请输入药品名称" clearable />

        </el-form-item>

        <el-form-item label="操作类型">

          <el-select v-model="queryForm.changeType" placeholder="请选择操作类型" clearable>

            <el-option :label="'入库'" :value="1" />

            <el-option :label="'出库'" :value="2" />

            <el-option :label="'调整'" :value="3" />

          </el-select>

        </el-form-item>

        <el-form-item label="操作时间">

          <el-date-picker v-model="queryForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" />

        </el-form-item>

        <el-form-item>

          <el-button type="primary" @click="handleSearch">

            <el-icon>

              <Search />

            </el-icon>搜索

          </el-button>

          <el-button @click="resetSearch">

            <el-icon>

              <Refresh />

            </el-icon>重置

          </el-button>

        </el-form-item>

      </el-form>

    </el-card>



    <!-- 操作按钮区域 -->

    <div class="operation-area">

      <el-button type="primary" @click="handleStockIn">

        <el-icon>

          <Plus />

        </el-icon>入库

      </el-button>

      <el-button type="warning" @click="handleStockOut">

        <el-icon>

          <Remove />

        </el-icon>出库

      </el-button>

      <el-button type="info" @click="handleStockAdjust">

        <el-icon>

          <Edit />

        </el-icon>调整

      </el-button>

    </div>



    <!-- 表格区域 -->

    <el-card class="table-area">

      <el-table v-loading="loading" :data="tableData" border style="width: 100%">

        <el-table-column type="index" label="序号" width="60" align="center" />

        <el-table-column label="药品信息" min-width="200">

          <template #default="{ row }">

            <div class="medicine-info">

              <div class="medicine-name">{{ row.medicineName }}</div>

              <div class="medicine-details" v-if="row.specification || row.manufacturer">

                <el-tag size="small" type="info" v-if="row.specification">

                  {{ row.specification }}

                </el-tag>

                <span class="manufacturer" v-if="row.manufacturer">

                  {{ row.manufacturer }}

                </span>

                <el-tag size="small" type="warning" v-if="row.prescriptionCategoryName">

                  {{ row.prescriptionCategoryName }}

                </el-tag>

              </div>

            </div>

          </template>

        </el-table-column>

        <el-table-column prop="changeQuantity" label="操作数量" width="100" align="center">

          <template #default="{ row }">

            <span :class="{ 
              'text-red': row.changeType === 2, 
              'text-green': row.changeType === 1,
              'text-orange': row.changeType === 3 
            }">

              {{ row.changeType === 2 ? '-' : '+' }}{{ Math.abs(row.changeQuantity) }}

            </span>

          </template>

        </el-table-column>

        <el-table-column prop="changeType" label="操作类型" width="100" align="center">

          <template #default="{ row }">

            <el-tag :type="getOperationTypeTag(row.changeType)">

              {{ getOperationTypeText(row.changeType) }}

            </el-tag>

          </template>

        </el-table-column>

        <el-table-column prop="beforeQuantity" label="变动前数量" width="100" align="center" />

        <el-table-column prop="afterQuantity" label="变动后数量" width="100" align="center" />

        <el-table-column prop="operatorName" label="操作人" width="120" align="center" />

        <el-table-column prop="operateTime" label="操作时间" width="180" align="center">

          <template #default="{ row }">

            {{ formatDateTime(row.operateTime) }}

          </template>

        </el-table-column>

        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />

      </el-table>



      <!-- 分页 -->

      <div class="pagination-container">

        <el-pagination 
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]" 
          :total="total"
          :disabled="loading"
          :current-page="queryForm.pageNum"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" />

      </div>

    </el-card>



    <!-- 操作对话框 -->

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false"
      destroy-on-close>

      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">

        <el-form-item label="药品" prop="medicineId">

          <el-select
            v-model="formData.medicineId"
            filterable
            remote
            :remote-method="handleMedicineSearch"
            :loading="searchLoading"
            placeholder="请输入药品名称搜索"
            style="width: 100%"
            @change="handleMedicineChange"
            clearable
          >
            <el-option
              v-for="item in medicineOptions"
              :key="item.medicineId"
              :label="item.medicineName"
              :value="item.medicineId"
            >
              <div class="medicine-option">
                <div class="medicine-info">
                  <span class="medicine-name">{{ item.medicineName }}</span>
                  <span class="medicine-spec">{{ item.specification }}</span>
                </div>
                <div class="medicine-manufacturer">{{ item.manufacturer }}</div>
              </div>
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="数量" prop="quantity">

          <el-input-number v-model="formData.quantity" :min="1" controls-position="right" style="width: 100%" />

        </el-form-item>

        <el-form-item label="存放位置" prop="warehouseLocation">

          <el-input v-model="formData.warehouseLocation" placeholder="请输入存放位置" />

        </el-form-item>

        <el-form-item label="备注" prop="remark">

          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" />

        </el-form-item>

      </el-form>

      <template #footer>

        <span class="dialog-footer">

          <el-button @click="dialogVisible = false">取消</el-button>

          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">

            确定

          </el-button>

        </span>

      </template>

    </el-dialog>

  </div>

</template>



<script setup>

import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'

import { ElMessage } from 'element-plus'

import { stockIn, stockOut, adjustStock, getStockRecords, searchMedicineList, getStockStats } from '../../api/stock/index.js'

import { formatDateTime } from '../../utils/dateUtil.js'

import { Search, Plus, Remove, Edit, Refresh } from '@element-plus/icons-vue'



// 数据定义

const loading = ref(false)

const tableData = ref([])

const total = ref(0)



// 查询表单

const queryForm = reactive({

  medicineName: '',

  changeType: '',

  dateRange: [],

  pageNum: 1,

  pageSize: 10

})



// 操作类型定义

const operationTypes = [

  { label: '入库', value: 1, tagType: 'success' },

  { label: '出库', value: 2, tagType: 'danger' },

  { label: '调整', value: 3, tagType: 'warning' }

]



// 获取操作类型文本

const getOperationTypeText = (type) => {

  const found = operationTypes.find(t => t.value === type)

  return found ? found.label : '未知'

}



// 获取操作类型标签样式

const getOperationTypeTag = (type) => {

  const found = operationTypes.find(t => t.value === type)

  return found ? found.tagType : 'info'

}



// 获取列表数据

const fetchList = async () => {

  loading.value = true

  try {

    const params = {

      pageNum: queryForm.pageNum,

      pageSize: queryForm.pageSize,

      medicineName: queryForm.medicineName || undefined,

      changeType: queryForm.changeType || undefined,

      startTime: queryForm.dateRange?.[0],

      endTime: queryForm.dateRange?.[1]

    }



    const res = await getStockRecords(params)

    console.log('列表数据响应:', res)

    

    if (res && res.code === 200 && res.data) {

      tableData.value = res.data.records || []

      total.value = res.data.total > 0 ? res.data.total : (res.data.records?.length || 0)
      
      queryForm.pageNum = res.data.current || queryForm.pageNum
      queryForm.pageSize = res.data.size || queryForm.pageSize

      if (tableData.value.length === 0 && queryForm.pageNum > 1) {

        queryForm.pageNum--

        await fetchList()

      }

    } else {

      ElMessage.error(res?.message || '获取数据失败')

    }

  } catch (error) {

    console.error('获取库存记录失败:', error)

    ElMessage.error(error.message || '获取库存记录失败')

  } finally {

    loading.value = false

  }

}



// 重置表单数据

const resetFormData = () => {

  Object.assign(formData, {

    medicineId: null,

    quantity: 1,

    warehouseLocation: '',

    remark: '',

    changeType: null,

    operatorId: 1 // 从登录用户中获取

  })

}



// 重置搜索条件

const resetSearch = () => {

  Object.assign(queryForm, {

    medicineName: '',

    changeType: '',

    dateRange: [],

    pageNum: 1,

    pageSize: 10

  })

  fetchList()

}



// 药品搜索相关

const medicineOptions = ref([])

const searchLoading = ref(false)



// 药品搜索处理

const handleMedicineSearch = async (query) => {

  if (!query) {

    medicineOptions.value = []

    return

  }

  searchLoading.value = true

  try {

    const res = await searchMedicineList({ medicineName: query })

    console.log('药品搜索结果:', res)

    if (res.code === 200 && res.data && res.data.records) {

      // 使用records数组作为选项数据

      medicineOptions.value = res.data.records.map(item => ({

        medicineId: item.medicineId,

        medicineName: item.medicineName,

        specification: item.specification,

        manufacturer: item.manufacturer

      }))

    } else {

      ElMessage.warning(res.message || '搜索药品失败')

    }

  } catch (error) {

    console.error('搜索药品失败:', error)

    ElMessage.error('搜索药品失败')

  } finally {

    searchLoading.value = false

  }

}



// 表单相关

const dialogVisible = ref(false)

const dialogType = ref('')

const dialogTitle = computed(() => {

  const titleMap = {

    in: '药品入库',

    out: '药品出库',

    adjust: '库存调整'

  }

  return titleMap[dialogType.value] || ''

})

const formRef = ref(null)

const submitLoading = ref(false)



const formData = reactive({

  medicineId: null,

  medicineName: '', // 添加药品名称字段

  quantity: 1,

  warehouseLocation: '',

  remark: '',

  changeType: null,

  operatorId: 1 // 从登录用户中获取

})



// 表单提交前的验证规则

const formRules = {

  medicineId: [{ required: true, message: '请选择药品', trigger: 'change' }],

  quantity: [{ required: true, message: '请输入数量', trigger: 'change' }],

  warehouseLocation: [{ required: true, message: '请输入存放位置', trigger: 'blur' }]

}



// 打开弹窗

const openDialog = (type) => {

  dialogType.value = type

  dialogVisible.value = true

  resetForm()

}



// 重置表单

const resetForm = () => {

  if (formRef.value) {

    formRef.value.resetFields()

  }

  resetFormData()

  medicineOptions.value = [] // 清空药品选项

}



// 表单提交处理

const handleSubmit = async () => {

  if (!formRef.value) return



  try {

    await formRef.value.validate()

    submitLoading.value = true



    const apiMap = {

      in: stockIn,

      out: stockOut,

      adjust: adjustStock

    }



    const api = apiMap[dialogType.value]

    if (!api) throw new Error('未知的操作类型')



    const res = await api(formData)

    if (res.code === 200) {

      ElMessage.success('操作成功')

      dialogVisible.value = false

      fetchList()

      fetchStats()

    } else {

      ElMessage.error(res.message || '操作失败')

    }

  } catch (error) {

    console.error('提交失败:', error)

    ElMessage.error(error.message || '操作失败')

  } finally {

    submitLoading.value = false

  }

}



// 分页处理

const handleSizeChange = (val) => {

  queryForm.pageSize = val

  queryForm.pageNum = 1

  fetchList()

}



const handleCurrentChange = (val) => {

  queryForm.pageNum = val

  fetchList()

}



// 药品选择改变时的处理

const handleMedicineChange = (value) => {

  const selectedMedicine = medicineOptions.value.find(item => item.medicineId === value)

  if (selectedMedicine) {

    formData.medicineName = selectedMedicine.medicineName

  }

}



// 统计数据

const stats = reactive({

  totalStock: 0,

  monthlyIn: 0,

  monthlyOut: 0,

  monthlyAdjust: 0

})



// 获取统计数据

const fetchStats = async () => {

  try {

    const res = await getStockStats()

    console.log('统计数据响应:', res)

    

    if (res && res.code === 200 && res.data) {

      // 更新统计数据，使用正确的字段名

      stats.totalStock = res.data.totalQuantity || 0

      stats.monthlyIn = res.data.monthlyIn || 0

      stats.monthlyOut = res.data.monthlyOut || 0

      stats.monthlyAdjust = res.data.warningCount || 0 // 这里使用warningCount作为调整数

    } else {

      console.warn('获取统计数据失败:', res?.message)

    }

  } catch (error) {

    console.error('获取统计数据失败:', error)

  }

}



// 操作按钮处理

const handleStockIn = () => {

  dialogType.value = 'in'

  dialogVisible.value = true

  resetForm()

}



const handleStockOut = () => {

  dialogType.value = 'out'

  dialogVisible.value = true

  resetForm()

}



const handleStockAdjust = () => {

  dialogType.value = 'adjust'

  dialogVisible.value = true

  resetForm()

}



// 初始化时获取数据

onMounted(() => {

  fetchList()

  fetchStats()

})



onUnmounted(() => {

  // 清除定时器

  if (statsTimer) {

    clearInterval(statsTimer)

  }

})

</script>



<style scoped>
.stock-container {

  padding: 20px;

}



.operation-area {

  margin: 20px 0;

  display: flex;

  gap: 10px;

}



.search-area,

.table-area {

  margin-bottom: 20px;

  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

}



.pagination-container {

  margin-top: 20px;

  padding: 10px 0;

  display: flex;

  justify-content: flex-end;

  background-color: #fff;

}



.medicine-info {

  display: flex;

  flex-direction: column;

  gap: 8px;

}



.medicine-name {

  font-weight: bold;

  color: #303133;

  font-size: 14px;

}



.medicine-details {

  display: flex;

  align-items: center;

  gap: 8px;

  flex-wrap: wrap;

}



.manufacturer {

  color: #909399;

  font-size: 12px;

}



.text-red {

  color: #f56c6c;

  font-weight: bold;

}



.text-green {

  color: #67c23a;

  font-weight: bold;

}



.text-orange {

  color: #e6a23c;

  font-weight: bold;

}



.medicine-option {

  display: flex;

  justify-content: space-between;

  align-items: center;

  padding: 8px 0;

}



.medicine-info {

  display: flex;

  flex-direction: column;

  gap: 4px;

}



.medicine-name {

  font-weight: bold;

  color: #303133;

}



.medicine-spec {

  font-size: 12px;

  color: #909399;

}



.medicine-manufacturer {

  font-size: 12px;

  color: #909399;

}



:deep(.el-select-dropdown__item) {

  padding: 0 12px;

}



/* 响应式样式 */

@media screen and (max-width: 768px) {

  .operation-area {

    flex-direction: column;

  }



  .search-area :deep(.el-form) {

    display: flex;

    flex-direction: column;

  }



  .search-area :deep(.el-form-item) {

    margin-right: 0;

    width: 100%;

  }



  :deep(.el-dialog) {

    width: 90% !important;

  }

}



.statistics-area {

  margin-bottom: 20px;

}



.statistic-card {

  height: 100px;

  transition: all 0.3s;

  cursor: pointer;

}



.statistic-card:hover {

  transform: translateY(-2px);

  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

}



.statistic-content {

  display: flex;

  flex-direction: column;

  justify-content: center;

  height: 100%;

  padding: 0 20px;

}



.statistic-title {

  font-size: 14px;

  color: #606266;

  margin-bottom: 8px;

}



.statistic-value {

  font-size: 24px;

  font-weight: bold;

  color: #303133;

}



.statistic-value.green {

  color: #67c23a;

}



.statistic-value.red {

  color: #f56c6c;

}



.statistic-value.orange {

  color: #e6a23c;

}



/* 表格样式优化 */

.el-table {

  margin-top: 20px;

  border-radius: 4px;

}



:deep(.el-table th) {

  background-color: #f5f7fa;

  color: #606266;

  font-weight: 600;

}



:deep(.el-table td) {

  padding: 8px 0;

}



:deep(.el-tag) {

  border-radius: 4px;

  font-size: 12px;

}



:deep(.el-tag--info) {

  background-color: #f4f4f5;

  border-color: #e9e9eb;

  color: #909399;

}



:deep(.el-tag--warning) {

  background-color: #fdf6ec;

  border-color: #faecd8;

  color: #e6a23c;

}



/* 搜索区域样式优化 */

.search-area {

  background-color: #fff;

  border-radius: 4px;

  padding: 20px;

}



/* 操作按钮样式优化 */

.operation-area {

  margin: 20px 0;

  display: flex;

  gap: 12px;

}



.operation-area .el-button {

  padding: 12px 20px;

}



/* 移动端适配 */

@media screen and (max-width: 768px) {

  .statistics-area .el-col {

    margin-bottom: 12px;

  }



  .operation-area {

    flex-direction: column;

  }



  .operation-area .el-button {

    width: 100%;

  }



  .search-area :deep(.el-form-item) {

    margin-bottom: 12px;

  }

}

:deep(.el-pagination) {
  padding: 0;
  margin: 0;
  font-weight: normal;
}

:deep(.el-pagination .el-select .el-input) {
  width: 100px;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin-right: 16px;
}
</style>
